package shin

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"local.public/innerpkg/logger"
	"local.public/internal/appconfig"
	"local.public/utils"
	"strings"
)

type WorkerStatusReq struct {
	MsgId      string   `json:"msgid,omitempty"`
	ClientId   string   `json:"client_id,omitempty"`
	IpAddr     string   `json:"ipaddr,omitempty"`
	MachineTag string   `json:"machine_tag,omitempty"`
	Frameworks []string `json:"frameworks,omitempty"`
	Status     string   `json:"status,omitempty"`
	StatusDesc string   `json:"status_desc,omitempty"`
}

type AiSubtaskStatusReq struct {
	MsgId       string `json:"msgid,omitempty"`
	ClientId    string `json:"client_id,omitempty"`
	MemberId    string `json:"member_id,omitempty"`
	TaskDBId    int    `json:"task_dbid,omitempty"`
	SubtaskDBId int    `json:"subtask_dbid,omitempty"`
	//Status        string `json:"status,omitempty"`
	SubtaskStatus string `json:"subtask_status,omitempty"`
	StepType      string `json:"step_type,omitempty"`
	StepNum       int    `json:"step_num,omitempty"`
	GoodsSn       string `json:"goods_sn,omitempty"`
	FragmentSn    string `json:"fragment_sn,omitempty"`
	InstanceSn    string `json:"instance_sn,omitempty"`
	FrameworkName string `json:"framework_name,omitempty"`
	GenerateKind  string `json:"generate_kind,omitempty"`
	VideoDuration int    `json:"video_duration,omitempty"`
}

type AiTaskStatusMqReq struct {
	MsgType       string `json:"msgtype"` //消息类型
	Status        string `json:"status,omitempty"`
	MemberId      string `json:"member_id,omitempty"`
	Desc          string `json:"desc,omitempty"`
	TaskDBId      int    `json:"task_dbid,omitempty"`
	TaskStatus    string `json:"task_status,omitempty"`
	FrameworkName string `json:"framework_name,omitempty"`
	GenerateKind  string `json:"generate_kind,omitempty"`
	GoodsSn       string `json:"goods_sn,omitempty"`
	FragmentSn    string `json:"fragment_sn,omitempty"`
	InstanceSn    string `json:"instance_sn,omitempty"`
	OutFilename   string `json:"outfile_filename,omitempty"`
	OutUrlpath    string `json:"outfile_urlpath,omitempty"`
	VideoDuration int    `json:"video_duration,omitempty"`
}

var IsShowWorkerStatusReportLog = false
var MapEdgeConfigCh map[string]chan bool
var MapEdgeConfigData map[string]string

func init() {
	MapEdgeConfigCh = make(map[string]chan bool)
	MapEdgeConfigData = make(map[string]string)
}
func MqttMsgHandler(client mqtt.Client, msg mqtt.Message) {

	sTopic := msg.Topic()

	availableSubjects := []string{"workeradmin/report/worker_status/", "workeradmin/report/ai_subtask_status/"}

	if !utils.PrefixInStringArr(sTopic, availableSubjects) {
		logger.Debug(sTopic + " 不符合前缀条件" + fmt.Sprintf("%v", availableSubjects))
		return
	} else {
		logger.Debug(sTopic + " 符合前缀条件" + fmt.Sprintf("%v", availableSubjects))
	}
	// 过滤 仅接受符合前缀要求的mqttclientid
	sClientId := utils.LastString(strings.Split(sTopic, "/"))
	if len(appconfig.GetConfig().LimitOptions.ClientIdPrefixArr) > 0 {
		if !utils.PrefixInStringArr(sClientId, appconfig.GetConfig().LimitOptions.ClientIdPrefixArr) {
			//logger.Debug(sClientId + " 不符合前缀条件" + fmt.Sprintf("%v", datastore.GetConfig().LimitOptions.ClientIdPrefixArr))
			return
		} else {
			if strings.HasPrefix(sClientId, "voice") {
				logger.Debug(sClientId + " 符合前缀条件" + fmt.Sprintf("%v", appconfig.GetConfig().LimitOptions.ClientIdPrefixArr))
			}
			//logger.Debug(sClientId + " 符合前缀条件" + PrintWorkerHasUntreatedSubtask())
		}
	}
	// 过滤 过滤掉在配置文件中要求排除掉的mqttclientid
	if len(appconfig.GetConfig().LimitOptions.ClientIdExcludeArr) > 0 {
		if utils.InStringArr(sClientId, appconfig.GetConfig().LimitOptions.ClientIdExcludeArr) {
			//logger.Debug(sClientId + " 符合排除条件" + fmt.Sprintf("%v", datastore.GetConfig().LimitOptions.ClientIdPrefixArr))
			return
		}
	}

	// 更新MapWorkerStatus的状态
	if strings.HasPrefix(sTopic, "workeradmin/report/worker_status/") { //收到worker上报来的worker状态
		handleWorkerStatus(sTopic, msg.Payload())
		return
	}
	if strings.HasPrefix(sTopic, "workeradmin/report/ai_subtask_status/") { //收到worker上报来的subtask状态
		HandleSubtaskStatus(sTopic, msg.Payload())
		return
	}

	logger.Debug("未处理的主题: %s 信息: %s\n", msg.Topic(), msg.Payload())

}

func handleWorkerStatus(topic string, payload []byte) {
	//sTopic := topic
	//sClientId := utils.LastString(strings.Split(sTopic, "/"))
	return
}

func HandleSubtaskStatus(topic string, payload []byte) {
	//sTopic := topic
	//sClientId := utils.LastString(strings.Split(sTopic, "/"))
	return
}

func HandleIdentifyResult(topic string, payload []byte) {
	//sTopic := topic
	//sClientId := utils.LastString(strings.Split(sTopic, "/"))

	//fmt.Println(utils.MqttSubscribeIdentifyResultPrefix+" sClientId is", sClientId)
	//fmt.Printf(utils.MqttSubscribeIdentifyResultPrefix+" msg.PayLoad: %s\n", string(payload))
	//更新MapWorkerStatus的状态,放到BusyWorkers或者NotBusyWorkers中
	return
}
